package com.scm.manager.impl;

import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.enums.*;
import com.scm.common.exception.ServiceException;
import com.scm.common.utils.DateUtils;
import com.scm.common.utils.StringUtils;
import com.scm.dto.req.inventory.CreateInventoryOutByOrderReq;
import com.scm.dto.req.order.OrderBeanReq;
import com.scm.dto.req.order.OrderImportBean;
import com.scm.converter.OrderConverter;
import com.scm.dto.resp.invent.ScmInventoryOutDetailDo;
import com.scm.dto.resp.order.OrderDetailDo;
import com.scm.dto.resp.order.OrderProductDo;
import com.scm.dto.resp.order.QueryOrderZhipairenResp;
import com.scm.dto.resp.product.ProductSyncStatus;
import com.scm.dto.resp.product.ScmProductDo;
import com.scm.manager.OrderManager;
import com.scm.persist.model.*;
import com.scm.persist.mybatis.ScmOrderInvoiceMapper;
import com.scm.service.*;
import com.scm.system.service.ISysUserService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class OrderManagerImpl implements OrderManager {


    @Autowired
    private ISysUserService userService;

    @Autowired
    IScmOrderService orderService;

    @Autowired
    IScmProductService productService;

    @Autowired
    IScmOrderProductService orderProductService;

    @Autowired
    private IScmOrderBaobeiService orderBaobeiService;

    @Autowired
    private IScmOrderLogService orderLogService;

    @Autowired
    private IScmOrderOperationService scmOrderOperationService;

    @Autowired
    private IScmInventoryOutService inventoryOutService;

    @Autowired
    private IScmInventoryStashService inventoryStashService;

    @Autowired
    private ScmOrderInvoiceMapper scmOrderInvoiceMapper;


    @Override
    public void importOmsOrder(SysUser sysUser,List<OrderImportBean> orderImportModelList) {

        if(CollectionUtils.isEmpty(orderImportModelList)){
            return;
        }

        List<OrderBeanReq> orderBeanList = OrderConverter.convertOMSOrdersToScmOrders(sysUser.getTenantId(),orderImportModelList);

        if(CollectionUtils.isEmpty(orderBeanList)){
            return;
        }

        for (OrderBeanReq orderBean : orderBeanList) {

            long scmOrderid = orderService.saveOrUpdateScmOrder(sysUser,orderBean.getOrder());

            orderProductService.saveOrUpdateScmOrderProduct(sysUser,scmOrderid,orderBean.getOrderProductList());

        }

    }

    @Override
    public OrderDetailDo getOrderDetailById(Long orderId) {

        ScmOrder scmOrder = orderService.selectScmOrderById(orderId);

        List<ScmOrderProduct> list = orderProductService.selectScmOrderProductByOrderId(orderId);
        ScmOrderOperation scmOrderOperation = orderService.selectByScmOrderId(orderId);

        ScmOrderInvoiceExample example = new ScmOrderInvoiceExample();
        example.createCriteria().andScmOrderIdEqualTo(orderId);
        List<ScmOrderInvoice> scmOrderInvoices = scmOrderInvoiceMapper.selectByExample(example);
        ScmOrderInvoice scmOrderInvoice ;
        if(CollectionUtils.isEmpty(scmOrderInvoices)){
            scmOrderInvoice = new ScmOrderInvoice();
        }else {
            scmOrderInvoice = scmOrderInvoices.get(0);
        }
        OrderDetailDo orderDetailDo =  OrderConverter.convertSCMSOrdersToOrderDetailDo(scmOrder,list,scmOrderOperation,scmOrderInvoice);

        return orderDetailDo;

    }

    @Override
    public void saveBaobei(String omsOrderId, SysUser loginSysUser) {

        ScmOrderBaobei record = new ScmOrderBaobei();
        record.setOmsOrderId(omsOrderId);
        record.setBaobeiren(String.valueOf(loginSysUser.getUserId()));
        record.setBaobeiTime(System.currentTimeMillis());
        record.setBaobeiTimeStr(DateUtils.getTime());
        record.setCreateTime(System.currentTimeMillis());
        record.setCreateUser(loginSysUser.getLoginName());
        record.setTenantId(loginSysUser.getTenantId());
        orderBaobeiService.saveBaobei(record);

        //维护订单报备记录
        orderService.updateBaobeiStatus(omsOrderId);


    }


    @Override
    public void uploadCredentials(Long omsOrderId, SysUser loginSysUser, String filePath) {

        ScmOrderOperation scmOrderOperation = new ScmOrderOperation();
        scmOrderOperation.setReceiptFile(filePath);
        scmOrderOperation.setUploadReceiptFileTime(System.currentTimeMillis());
        scmOrderOperation.setUploadReceiptFileUser(loginSysUser.getLoginName());
        scmOrderOperation.setScmOrderId(omsOrderId);
        ScmOrder scmOrder = orderService.selectScmOrderById(omsOrderId);
        if(scmOrder == null){
            throw new RuntimeException("未找到订单信息");
        }
        //scmOrder.setOrderStatus(OrderStatus.Confirm);
        scmOrder.setOrderStatus(OrderStatus.uploadSignedReceipt.getCode());
        scmOrder.setOrderStatusDesc(OrderStatus.uploadSignedReceipt.getName());
        scmOrder.setReceiptFielStatus(ReceiptFielStatusEnum.uploadSignedReceipt.getCode());
        orderService.updateScmOrder(scmOrder,loginSysUser);
        //修改订单状态已上传签收单
        orderService.updateOrderStatus(scmOrder.getId(), OrderStatus.uploadSignedReceipt);
        int i = orderService.updateScmOrderOperation(scmOrderOperation);

        ScmOrderLog orderLog = OrderConverter.createOrderLog(omsOrderId,OrderOperationType.uploadCredentials,loginSysUser,loginSysUser.getLoginName()+"上传了签收单，订单id:"+omsOrderId);
        orderLogService.saveOrderLog(orderLog);

    }

    @Override
    public void uploadWaitReceipt(Long omsOrderId, SysUser loginSysUser, String filePath,String orderType) {
        ScmOrder scmOrder = orderService.selectScmOrderById(omsOrderId);
        if(scmOrder == null){
            throw new RuntimeException("未找到订单信息");
        }
        scmOrder.setOrderType(orderType);
        orderService.updateScmOrder(scmOrder,loginSysUser);
        ScmOrderOperation scmOrderOperation = new ScmOrderOperation();
        scmOrderOperation.setWaitReceiptFile(filePath);
        scmOrderOperation.setUploadWaitReceiptFileTime(System.currentTimeMillis());
        scmOrderOperation.setUploadWaitReceiptFileUser(loginSysUser.getLoginName());
        scmOrderOperation.setScmOrderId(omsOrderId);
        orderService.updateScmOrderOperation(scmOrderOperation);


        scmOrder.setOrderStatus(OrderStatus.uploadPendingReceiptForm.getCode());
        scmOrder.setOrderStatusDesc(OrderStatus.uploadPendingReceiptForm.getName());
        scmOrder.setReceiptFielStatus(ReceiptFielStatusEnum.uploadPendingReceiptForm.getCode());
        orderService.updateScmOrder(scmOrder,loginSysUser);
        //修改订单状态已上传签收单
        //orderService.updateOrderStatus(scmOrder.getId(), OrderStatus.uploadPendingReceiptForm);
        int i = orderService.updateScmOrderOperation(scmOrderOperation);

        ScmOrderLog orderLog = OrderConverter.createOrderLog(omsOrderId,OrderOperationType.uploadWaitReceipt,loginSysUser,loginSysUser.getLoginName()+"上传了待签收单，订单id:"+omsOrderId);
        orderLogService.saveOrderLog(orderLog);
    }

    @Override
    public void uploaduploadInvoice(Long omsOrderId, SysUser loginSysUser, String filePath, String orderType) {

        ScmOrder scmOrder = orderService.selectScmOrderById(omsOrderId);
        if(scmOrder == null){
            throw new RuntimeException("未找到订单信息");
        }
        ScmOrderInvoiceExample example = new ScmOrderInvoiceExample();
        example.createCriteria().andScmOrderIdEqualTo(omsOrderId);
        List<ScmOrderInvoice> scmOrderInvoices = scmOrderInvoiceMapper.selectByExample(example);
        ScmOrderInvoice scmOrderInvoice = new ScmOrderInvoice();
        scmOrderInvoice.setInvoiceFile(filePath);
        scmOrderInvoice.setUploadInvoiceFileTime(System.currentTimeMillis());
        scmOrderInvoice.setUploadInvoiceFileUser(loginSysUser.getLoginName());
        scmOrderInvoice.setScmOrderId(omsOrderId);
        if(CollectionUtils.isEmpty(scmOrderInvoices)){
            scmOrderInvoice.setScmOrderId(omsOrderId);
            scmOrderInvoice.setTenantId(scmOrder.getTenantId());
            scmOrderInvoice.setCreateTime(System.currentTimeMillis());
            scmOrderInvoice.setCreateUser(loginSysUser.getUserName());
            scmOrderInvoiceMapper.insert(scmOrderInvoice);
        }else {
            ScmOrderInvoiceExample exampleUpdate = new ScmOrderInvoiceExample();
            ScmOrderInvoiceExample.Criteria criteria = exampleUpdate.createCriteria();
            criteria.andScmOrderIdEqualTo(omsOrderId);
            scmOrderInvoice.setUpdateTime(System.currentTimeMillis());
            scmOrderInvoice.setUpdateUser(loginSysUser.getUserName());
            scmOrderInvoiceMapper.updateByExampleSelective(scmOrderInvoice,exampleUpdate);
        }
        scmOrder.setInvoiceStatus("1");
        orderService.updateScmOrder(scmOrder,loginSysUser);


        //orderService.updateScmOrderOperation(scmOrderOperation);
        ScmOrderLog orderLog = OrderConverter.createOrderLog(omsOrderId,OrderOperationType.uploadInvoice,loginSysUser,loginSysUser.getLoginName()+"上传了发票，订单id:"+omsOrderId);
        orderLogService.saveOrderLog(orderLog);


    }

    @Override
    public QueryOrderZhipairenResp queryOrderZhipairen(Long id ,SysUser loginSysUser) {

        List<SysUser> sysUsers = userService.selectAllUserList();

        ScmOrder scmOrder = orderService.selectScmOrderById(id);

        List<ScmOrderBaobei> orderBaobeiList  = orderBaobeiService.selectOrderBaobei(scmOrder.getOrderid());

        return   QueryOrderZhipairenResp.builder().list(OrderConverter.getAllWaitZhipaiUser(scmOrder,sysUsers,orderBaobeiList)).scmOrder(scmOrder).build();

    }

    @Override
    public void confirmOrder(Long id, SysUser loginSysUser) {

        //修改订单状态为确认
        orderService.updateOrderStatus(id, OrderStatus.Confirm);

        //修改订单业务
        ScmOrderOperation orderOperation = new ScmOrderOperation();
        orderOperation.setScmOrderId(id);
        orderOperation.setConfireTime(System.currentTimeMillis());
        orderOperation.setConfireTimeStr(DateUtils.getTime());
        orderOperation.setConfireUser(String.valueOf(loginSysUser.getUserId()));
        scmOrderOperationService.updateOrderOperationByOrderId(orderOperation);

        ScmOrderLog orderLog = OrderConverter.createOrderLog(id,OrderOperationType.Confirm,loginSysUser,loginSysUser.getLoginName()+"确认了订单，订单id:"+id);

        orderLogService.saveOrderLog(orderLog);
    }

    @Override
    public List<ProductSyncStatus> syncScmOrderProduct(SysUser loginSysUser,Long orderId) {

        List<ProductSyncStatus> result = Lists.newArrayList();

        List<ScmOrderProduct> list = orderProductService.selectScmOrderProductByOrderId(orderId);
        if(CollectionUtils.isEmpty(list)){
            return result;
        }

        list.forEach(scmOrderProduct -> {

            ProductSyncStatus productSyncStatus = new ProductSyncStatus();

            if(scmOrderProduct.getProductId()==null||scmOrderProduct.getProductId()==0){
                productSyncStatus = productService.syncProduct(loginSysUser.getTenantId(), ProductSourceEnum.OMS.getCode(),scmOrderProduct.getProductCode(), String.valueOf(loginSysUser.getUserId()));

                if(ProductSyncStatusEnum.Success.getCode().equals(productSyncStatus.getStatus().getCode())
                || ProductSyncStatusEnum.SyncEd.getCode().equals(productSyncStatus.getStatus().getCode())){
                    scmOrderProduct.setProductId(productSyncStatus.getProductId());
                    orderProductService.updateByPrimaryKey(scmOrderProduct);
                }
            }else{
                productSyncStatus.setProductCode(scmOrderProduct.getProductCode());
                productSyncStatus.setStatus(ProductSyncStatusEnum.SyncEd);
                productSyncStatus.setMsg("商品编号"+scmOrderProduct.getProductCode()+"已存在，无需同步");
            }

            result.add(productSyncStatus);
        });


        ScmOrderLog orderLog = OrderConverter.createOrderLog(orderId,OrderOperationType.SyncScmOrderProduct,loginSysUser,loginSysUser.getLoginName()+"执行订单商品同步才做，订单id:"+orderId);

        orderLogService.saveOrderLog(orderLog);


        return result;
    }

    @Override
    public int updateScmOrder(SysUser loginSysUser,ScmOrder scmOrder) {

        orderService.updateScmOrder(scmOrder,loginSysUser);

        ScmOrderLog orderLog = OrderConverter.createOrderLog(scmOrder.getId(),OrderOperationType.Update,loginSysUser,loginSysUser.getLoginName()+"执行订单更新才做，订单id:"+scmOrder.getId());

        orderLogService.saveOrderLog(orderLog);
        return 1;
    }

    @Override
    public ScmInventoryOut orderToOutInventory(Long id, SysUser loginSysUser) {

        ScmOrder scmOrder =  orderService.selectScmOrderById(id);

        if(scmOrder==null){
            throw new ServiceException("未找到订单信息！");
        }

        //订单验证逻辑
        List<OrderProductDo> list = orderService.selectScmOrderProductList(loginSysUser.getTenantId(),id);
        if(CollectionUtils.isEmpty(list)){
            throw new ServiceException("未找到该订单对应的商品信息！");
        }


        ScmInventoryOut scmInventoryOut = new ScmInventoryOut();

        scmInventoryOut.setName("销售单转出库单,OMS订单号:"+scmOrder.getOrderid());
        scmInventoryOut.setOutDatetime(System.currentTimeMillis());
        scmInventoryOut.setOutDatetimeStr(DateUtils.getDate());
        scmInventoryOut.setOrderId(String.valueOf(scmOrder.getId()));

       return scmInventoryOut;


    }

    @Override
    public  List<ScmInventoryOutDetailDo> queryOrderProductToOutInventory(Long orderId, SysUser loginSysUser) {

        List<OrderProductDo> list = orderService.selectScmOrderProductList(loginSysUser.getTenantId(),orderId);

        List<ScmInventoryOutDetailDo> details = Lists.newArrayList();

        for (OrderProductDo orderProductDo : list) {

            ScmInventoryOutDetailDo inventoryOutDetail= new ScmInventoryOutDetailDo();
            inventoryOutDetail.setOutStashAmount(orderProductDo.getProductPriceStr());
            inventoryOutDetail.setProductCount(orderProductDo.getProductCount());

            //填充商品信息
            ScmProductDo productDo = productService.selectScmProductById(loginSysUser.getTenantId(),orderProductDo.getProductId());
            inventoryOutDetail.setProductCode(productDo.getProductCode());
            inventoryOutDetail.setProductName(productDo.getProductName());
            inventoryOutDetail.setProductId(productDo.getId());
            inventoryOutDetail.setProductUnit(productDo.getProductUnit());

            //出库金额
            inventoryOutDetail.setOutStashAmount(orderProductDo.getProductPriceStr());

            //出库数量
            inventoryOutDetail.setOutCount(orderProductDo.getProductCount());

            //如果匹配商品只有一个库存信息，则自动赋值商品的库存信息
            if(orderProductDo.isSingleStash()){
                inventoryOutDetail.setStashId(orderProductDo.getStashId());

                ScmInventoryStash inventoryStash = inventoryStashService.selectScmInventoryStashById(orderProductDo.getStashId());
                if(inventoryStash!=null){
                    inventoryOutDetail.setStashName(inventoryStash.getName());
                }

                inventoryOutDetail.setAvailableCount(orderProductDo.getProductInventoryCount());

                ScmInventoryStashProduct inventoryStashProduct = orderProductDo.getInventoryStashProduct();
                if(inventoryStashProduct!=null){
                    inventoryOutDetail.setStashProductId(inventoryStashProduct.getId());
                }


            }
            details.add(inventoryOutDetail);

        }

        return details;

    }

}
